package com.kqb.sgpicturebackend.controller;


import com.kqb.sgpicturebackend.common.BaseResponse;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.common.ResultUtils;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;


/**
 * 用户接口
 *
 * @author 杉果树皮
 */
@RestController
@Slf4j
@Api(tags = "文件上传下载")
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile) {
        //得到文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //文件路径
        String filePath = String.format("/test/%s", originalFilename);
        File tempFile = null;
        try {
            tempFile = File.createTempFile(filePath, null);
            multipartFile.transferTo(tempFile);
            cosManager.putObject(filePath, tempFile);
            return ResultUtils.success(filePath);
        } catch (Exception e) {
            log.error("上传文件失败:{}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");

        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("临时文件删除失败:{}", filePath);
                }
            }
        }

    }

    @PostMapping("/download")
    @ApiOperation(value = "下载文件")
    public void downloadFile(String filePath, HttpServletResponse response) throws IOException {
        COSObjectInputStream objectContent = null;
        try {
            COSObject object = cosManager.getObject(filePath);
            objectContent = object.getObjectContent();
            //处理输入流，写到浏览器
            byte[] byteArray = IOUtils.toByteArray(objectContent);

            //设置响应头，控制浏览器下载该文件
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            //设置响应头，设置字节流
            response.setContentType("application/octet-stream");

            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(byteArray);
            outputStream.flush();
        } catch (Exception e) {
            log.error("下载文件失败:{}", filePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载文件失败");
        } finally {
            if (objectContent != null) {
                objectContent.close();
            }
        }


    }

}
